package com.tiezhu.springdemo.controller;



import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.tiezhu.springdemo.Agora.RtcTokenBuilder;
import com.tiezhu.springdemo.Redis.RedisUtil;
import com.tiezhu.springdemo.bean.FeedHistory;
import com.tiezhu.springdemo.bean.User;
import com.tiezhu.springdemo.bean.UserLogin;
import com.tiezhu.springdemo.mapper.HistoryMapper;
import com.tiezhu.springdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class UserController {

    static String appId = "9d76aef0949a4d9aaac9100f31652021";
    //    static String appCertificate = "5CFd2fd1755d40ecb72977518be15d3b";
    static String appCertificate = "71b403579c394c0885b1393f4f820770";
    static String channelName = "test";
    static String userAccount = "2082341273";
    static int uid = 0;
    static int expirationTimeInSeconds = 3600;


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HistoryMapper historyMapper;

    @PostMapping("/login")
    @ResponseBody
    public Map<String,Object>  queryUserByName(@RequestBody UserLogin userLogin){
        Map<String,Object> hashMap= new LinkedHashMap<>();
        String userName = userLogin.getUserName();
        String passWord = userLogin.getPassWord();
        if (!userLogin.getCode().equals(redisUtil.get(userLogin.getCodeKey())))
        {
            User user = new User();
            hashMap.put("status",1);
            hashMap.put("msg","code error! ");
            hashMap.put("User",user);
            return hashMap;
        }
        List<User> userList = userMapper.queryUserByName(userName);
        System.out.println(userList);
        if (userList.size() == 0){
            User user = new User();
            hashMap.put("status",1);
            hashMap.put("msg","账号错误");
            hashMap.put("User",user);
            System.out.println(hashMap);
            return hashMap;
        }else {
            User user = userList.get(0);
            String usr = user.getUserName();
            String pwd = user.getPassWord();
            if (userName.equals(usr) && passWord.equals(pwd) ){
                hashMap.put("status",0);
                hashMap.put("msg","登录成功");
                hashMap.put("User",user);
                hashMap.put("Token",getToken());
                hashMap.put("loginToken",getLoginToken(userLogin.getUserName(),userLogin.getPassWord()));
                redisUtil.set(user.getUserName(),getLoginToken(userLogin.getUserName(),userLogin.getPassWord()),60*60*24*15);
                return hashMap;
            }
            else{
                hashMap.put("status",1);
                hashMap.put("msg","密码错误");
                hashMap.put("User",new User());
                System.out.println(hashMap);
                return hashMap;
            }
        }

    }

    @GetMapping("/queryUserById")
    @ResponseBody
    public User  queryUserById(@RequestParam("id")int id){
        User user = new User();
        user = userMapper.queryUserById(id);
        return user;
    }


    @PostMapping("/addUser")
    public Map<String,Object> addUser(@RequestBody User user){
        Map<String,Object> hashMap= new LinkedHashMap<>();
        System.out.println(user.toString());
        List<User> userList = userMapper.queryUserByName(user.getUserName());
        if (userList.size() != 0){
            hashMap.put("status",1);
            hashMap.put("msg","用户名已存在");
            System.out.println("用户名已存在");
            return hashMap;
        }else {
            int i = userMapper.addUser(user);
            if (i == 1){
                hashMap.put("status",0);
                hashMap.put("msg","注册成功");
                hashMap.put("User",user);
                System.out.println("注册成功");
                return hashMap;
            }else {
                hashMap.put("status",1);
                hashMap.put("msg","注册失败");
                hashMap.put("User",user);
                System.out.println("注册失败");
                return hashMap;
            }
        }
    }

    @PostMapping("/updateUser")
    public Map<String,Object> updateUser(@RequestBody User user){
        Map<String,Object> hashMap= new LinkedHashMap<>();
        System.out.println(user.toString());
        int i = userMapper.updateUser(new User((user.getId()),
                user.getUserName(),
                user.getPassWord(),
                user.getRealName()));
        List<User> userList = userMapper.queryUserByName(user.getUserName());
        if (i == 1){
            user = userList.get(0);
            hashMap.put("status",0);
            hashMap.put("msg","修改成功");
            hashMap.put("User",user);
            return hashMap;
        }else {
            user = userList.get(0);
            hashMap.put("status",1);
            hashMap.put("msg","修改失败");
            hashMap.put("User",user);
            return hashMap;
        }
    }

    @GetMapping("/deleteUserByName")
    @ResponseBody
    public String deleteUserByName(@RequestParam("username")String userName){
        int i = userMapper.deleteUserByName(userName);
        if (i == 1){
            return "ok";
        }else {
            return "no";
        }
    }


    @GetMapping("/autologin")
    @ResponseBody
    public Map<String,Object> autoLogin(@RequestParam("username") String userName ,@RequestHeader("token") String token){
        HashMap<String,Object> hashMap = new LinkedHashMap<>();
        if (!redisUtil.get(userName).equals(token)) {
           hashMap.put("status",1);
           hashMap.put("msg","自动登陆已过期");
           hashMap.put("User",new User());
           return hashMap;
        }
        List<User> userList = userMapper.queryUserByName(userName);
        User user = userList.get(0);
        hashMap.put("status",0);
        hashMap.put("msg","登录成功");
        hashMap.put("User",user);
        hashMap.put("Token",getToken());
        hashMap.put("loginToken",getLoginToken(user.getUserName(),user.getPassWord()));
        redisUtil.set(user.getUserName(),getLoginToken(user.getUserName(),user.getPassWord()),60*60*24*15);
        return hashMap;

    }

    @GetMapping("/test")
    public List<FeedHistory> test(){
        List<FeedHistory> feedHistoryList = historyMapper.queryHistoryByOwnerName("admin");
        System.out.println(feedHistoryList);
        return feedHistoryList;
    }

    public String  getToken(){
        RtcTokenBuilder token = new RtcTokenBuilder();
        int timestamp = (int)(System.currentTimeMillis() / 1000 + expirationTimeInSeconds);
        String result = token.buildTokenWithUid(appId, appCertificate,
                channelName, uid, RtcTokenBuilder.Role.Role_Publisher, timestamp);
        return result;
    }

    public String getLoginToken(String userName,String passWord){
        String token="";
        token = JWT.create().withAudience(userName)
                .sign(Algorithm.HMAC256(passWord));
        return token;
    }

}
